import sys
import random
import grader
import parse
import copy


def random_play_single_ghost(problem):
    # Your p1 code here
    seed = problem['seed']
    random.seed(seed, version=1)
    round = 0
    score = 0
    solution = 'seed: ' + str(seed) + '\n'
    queue = ['P'] + problem['ghostList']

    while len(problem['pacmanLoc']) > 0 and len(problem['foodLoc']) > 0:
        if round == 0:
            solution = pack_solution(solution, round, problem['map'], '', '', '',
                                     problem['pacmanLoc'], problem['ghostLoc'], problem['foodLoc'])
        else:
            ch = queue.pop(0)
            queue.append(ch)
            choose, score = move(ch, problem['map'], problem['pacmanLoc'],
                                 problem['ghostLoc'], problem['foodLoc'], score)
            solution = pack_solution(solution, round, problem['map'], ch, choose, score,
                                     problem['pacmanLoc'], problem['ghostLoc'], problem['foodLoc'])
        round += 1

    if len(problem['foodLoc']) == 0:
        winner = 'Pacman'
    else:
        winner = 'Ghost'

    solution += f"WIN: {winner}"

    return solution


def pack_solution(solution, round, map, ch, dir, score, pacmanLoc, ghostLoc, foodLoc):
    tempMap = copy.deepcopy(map)
    if round == 0:
        solution += f"{round}\n"
    else:
        solution += f"{round}: {ch} moving {dir}\n"

    if len(pacmanLoc) > 0:
        tempMap[pacmanLoc[0]][pacmanLoc[1]] = 'P'

    if len(foodLoc) > 0:
        for food in foodLoc.keys():
            tempMap[food[0]][food[1]] = '.'

    if len(ghostLoc) > 0:
        for key in ghostLoc.keys():
            tempMap[ghostLoc[key][0]][ghostLoc[key][1]] = key

    for row in tempMap:
        solution += ''.join(row) + '\n'

    solution += f"score: {score}\n" if round != 0 else ""
    return solution


def get_new_directions(ch, map, location, ghostLoc):
    availableDirs = []
    newLocDir = {}

    if ch == 'P':
        # check east
        if map[location[0]][location[1] + 1] != '%':
            availableDirs.append('E')
            newLocDir['E'] = [location[0], location[1] + 1]
        # check north
        if map[location[0] - 1][location[1]] != '%':
            availableDirs.append('N')
            newLocDir['N'] = [location[0] - 1, location[1]]
        # check south
        if map[location[0] + 1][location[1]] != '%':
            availableDirs.append('S')
            newLocDir['S'] = [location[0] + 1, location[1]]
        # check west
        if map[location[0]][location[1] - 1] != '%':
            availableDirs.append('W')
            newLocDir['W'] = [location[0], location[1] - 1]
    else:
        # check east
        if map[location[0]][location[1]+1] != '%' and \
                [location[0], location[1] + 1] not in ghostLoc.values():
            availableDirs.append('E')
            newLocDir['E'] = [location[0], location[1] + 1]
        # check north
        if map[location[0]-1][location[1]] != '%' and \
                [location[0] - 1, location[1]] not in ghostLoc.values():
            availableDirs.append('N')
            newLocDir['N'] = [location[0] - 1, location[1]]
        # check south
        if map[location[0]+1][location[1]] != '%' and \
                [location[0] + 1, location[1]] not in ghostLoc.values():
            availableDirs.append('S')
            newLocDir['S'] = [location[0] + 1, location[1]]
        # check west
        if map[location[0]][location[1]-1] != '%' and \
                [location[0], location[1] - 1] not in ghostLoc.values():
            availableDirs.append('W')
            newLocDir['W'] = [location[0], location[1] - 1]

    choose = random.choice(tuple(availableDirs))
    newLocDir = newLocDir[choose]

    return choose, newLocDir


def move(ch, map, pacmanLoc, ghostLoc, foodLoc, score):
    if ch == 'P':
        location = pacmanLoc
    else:
        location = ghostLoc[ch]
    choose, newLoc = get_new_directions(ch, map, location, ghostLoc)

    if ch == 'P':
        # check if pacman is moving to a ghost
        if [newLoc[0], newLoc[1]] in ghostLoc.values():
            pacmanLoc.clear()
            score -= 501
        # check if pacman is moving to a food
        elif (newLoc[0], newLoc[1]) in foodLoc:
            del foodLoc[(newLoc[0], newLoc[1])]
            pacmanLoc[0] = newLoc[0]
            pacmanLoc[1] = newLoc[1]
            score += 9
            if len(foodLoc) == 0:
                score += 500
        # check if pacman is moving to a space
        else:
            pacmanLoc[0] = newLoc[0]
            pacmanLoc[1] = newLoc[1]
            score -= 1
    else:
        # check if ghost is moving to pacman
        if newLoc[0] == pacmanLoc[0] and newLoc[1] == pacmanLoc[1]:
            pacmanLoc.clear()
            score -= 500
        ghostLoc[ch] = [newLoc[0], newLoc[1]]

    return choose, score


if __name__ == "__main__":
    try:
        test_case_id = int(sys.argv[1])
    except:
        test_case_id = -6
    problem_id = 1
    grader.grade(problem_id, test_case_id,
                 random_play_single_ghost, parse.read_layout_problem)
